import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, DatePicker } from 'antd';
import { UserOutlined, FileOutlined, EyeOutlined, LikeOutlined } from '@ant-design/icons';
import { Line } from '@ant-design/plots';
import dayjs from 'dayjs';
import styled from 'styled-components';
import { request } from '@/utils/request';
import Loading from '@/components/Loading';

const { RangePicker } = DatePicker;

// 添加动画样式
const AnimatedCard = styled(Card)`
  transition: all 0.3s ease-in-out;
  transform: translateY(0);

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  }
`;

const StatisticValue = styled.div`
  .ant-statistic-content-value {
    transition: all 0.3s ease-out;
    display: inline-block;
    
    &.updated {
      animation: numberChange 0.5s ease-out;
    }
  }

  @keyframes numberChange {
    0% {
      transform: translateY(-20px);
      opacity: 0;
    }
    100% {
      transform: translateY(0);
      opacity: 1;
    }
  }
`;

const ChartContainer = styled.div`
  opacity: 0;
  transform: translateY(20px);
  animation: slideUp 0.6s ease-out forwards;
  
  @keyframes slideUp {
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
`;

const DashboardContainer = styled.div`
  position: relative;
  min-height: 400px;
`;

interface TrendData {
  date: string;
  value: number;
  type: string;
}

interface DashboardStats {
  totalUsers: number;
  totalPosts: number;
  totalViews: number;
  totalLikes: number;
  trend: TrendData[];
}

const Dashboard: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState<DashboardStats>({
    totalUsers: 0,
    totalPosts: 0,
    totalViews: 0,
    totalLikes: 0,
    trend: [],
  });
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(7, 'day'),
    dayjs(),
  ]);
  const [updateKey, setUpdateKey] = useState(0);

  const fetchStats = async () => {
    try {
      setLoading(true);
      const data = await request.get<DashboardStats>('/dashboard/stats', {
        params: {
          startDate: dateRange[0].format('YYYY-MM-DD'),
          endDate: dateRange[1].format('YYYY-MM-DD'),
        },
      });
      setStats(data);
      setUpdateKey(prev => prev + 1);
    } catch (error) {
      console.error('获取仪表盘数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStats();
  }, [dateRange]);

  const StatisticCard = ({ title, value, prefix }: { title: string; value: number; prefix: React.ReactNode }) => (
    <AnimatedCard>
      <StatisticValue key={`${value}-${updateKey}`}>
        <Statistic
          title={title}
          value={value}
          prefix={prefix}
          formatter={(val) => (
            <span className="updated">{val}</span>
          )}
        />
      </StatisticValue>
    </AnimatedCard>
  );

  const renderContent = () => (
    <>
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col span={24}>
          <RangePicker
            value={dateRange}
            onChange={(dates) => dates && setDateRange(dates as [dayjs.Dayjs, dayjs.Dayjs])}
            allowClear={false}
            style={{ float: 'right' }}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={6}>
          <StatisticCard
            title="总用户数"
            value={stats.totalUsers}
            prefix={<UserOutlined />}
          />
        </Col>
        <Col span={6}>
          <StatisticCard
            title="文章数量"
            value={stats.totalPosts}
            prefix={<FileOutlined />}
          />
        </Col>
        <Col span={6}>
          <StatisticCard
            title="总浏览量"
            value={stats.totalViews}
            prefix={<EyeOutlined />}
          />
        </Col>
        <Col span={6}>
          <StatisticCard
            title="总点赞数"
            value={stats.totalLikes}
            prefix={<LikeOutlined />}
          />
        </Col>
      </Row>
      <Row style={{ marginTop: 16 }}>
        <Col span={24}>
          <AnimatedCard title="趋势图">
            <ChartContainer>
              <Line
                data={stats.trend}
                xField="date"
                yField="value"
                seriesField="type"
                height={300}
                animation={{
                  appear: {
                    animation: 'wave-in',
                    duration: 1000,
                  },
                }}
                xAxis={{
                  type: 'time',
                  tickCount: 7,
                  animate: true,
                }}
                yAxis={{
                  title: {
                    text: '数量',
                  },
                  animate: true,
                }}
                tooltip={{
                  showMarkers: true,
                  showCrosshairs: true,
                  shared: true,
                }}
                point={{
                  size: 4,
                  shape: 'circle',
                  style: {
                    stroke: '#fff',
                    lineWidth: 2,
                    fillOpacity: 1,
                  },
                }}
                legend={{
                  position: 'top',
                  animate: true,
                }}
              />
            </ChartContainer>
          </AnimatedCard>
        </Col>
      </Row>
    </>
  );

  return (
    <DashboardContainer>
      {loading && !stats.trend.length ? (
        <Loading text="正在加载仪表盘数据..." />
      ) : (
        renderContent()
      )}
    </DashboardContainer>
  );
};

export default Dashboard; 